package agent_service

import (
	"fmt"
	"github.com/google/uuid"
	"github.com/tealeg/xlsx"
	"io/ioutil"
	"math/rand"
	"os"
	"peilian-api/app/global/common"
	"peilian-api/app/global/databases/tables"
	"peilian-api/app/global/errors"
	"peilian-api/app/global/log"
	"peilian-api/app/global/variable"
	"peilian-api/app/model"
	"peilian-api/utils/encrypt"
	"peilian-api/utils/sdk"
	"peilian-api/utils/tools"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/mitchellh/mapstructure"
)

type AgentService struct{}

// 获取所有的机构名称
func GetAgentName() []model.AgentName {
	var ea []model.AgentName
	a, err := new(tables.Agent).GetAgentList()
	if err != nil {
		return ea
	}
	for _, v := range a {
		ea = append(ea, model.AgentName{Id: int64(v.ID), AgentName: v.AgentName})
	}
	return ea
}

// 添加客户信息
func (a *AgentService) AddAgent(ctx *gin.Context, aar model.AgentAddReq) *errors.ErrRes {
	agentObj := new(tables.Agent)
	// 1. 先判断该用户是否是超级账户
	s, exist := ctx.Get("sto")
	if !exist {
		return errors.NewErrInfo(10001, fmt.Errorf("用户不存在"))
	}
	sto := tools.Sto{}
	mapstructure.Decode(s, &sto)
	if sto.Type != tables.UserTypeSadmin {
		return errors.NewErrInfo(10002, fmt.Errorf("您无权操作~"))
	}

	// 2. 校验数据+添加数据
	email := aar.Email
	// 3. 判断该邮件是否被占用
	arr, err := agentObj.GetAgentByWhere(map[string]interface{}{"email": email}, "")
	if err != nil {
		return errors.NewErrInfo(10003, fmt.Errorf(errors.DatabaseMySqlOptionFail))
	}
	for _, v := range arr {
		if v.Email == email {
			return errors.NewErrInfo(10004, fmt.Errorf("该用户已经存在"))
		}
	}

	// 4. 插入数据
	startTime := time.Unix(aar.ServiceStartTime/1000, 0)
	endTime := time.Unix(aar.ServiceEndTime/1000, 0)
	surplusTime := tools.DiffNatureDays(endTime, time.Now())
	startTime, _ = time.Parse("2006-01-02 15:04:05", startTime.Format("2006-01-02")+" 23:59:59")
	endTime, _ = time.Parse("2006-01-02 15:04:05", endTime.Format("2006-01-02")+" 23:59:59")
	if surplusTime <= 0 {
		surplusTime = 0
	}
	agent, err := agentObj.AddAgent(tables.Agent{
		Type:             "school",
		Email:            email,
		AgentName:        aar.AgentName,
		ConnectPeople:    aar.ConnectPeople,
		ConnectPhone:     aar.ConnectPhone,
		Counterpart:      aar.Counterpart,
		CounterpartPhone: aar.CounterpartPhone,
		ServiceStartTime: startTime,
		ServiceEndTime:   endTime,
		School:           aar.School,
		SurplusTime:      int64(surplusTime),
		IsSync:           aar.IsSync,
	})
	if agent.ID == 0 || err != nil {
		return errors.NewErrInfo(10005, fmt.Errorf(errors.DatabaseMySqlOptionFail))
	}
	// 5. 更新一下缓存数据
	loc := time.FixedZone("UTC+8", 8*60*60)
	t, _ := time.ParseInLocation("2006-01-02 15:04:05", endTime.Format("2006-01-02")+" 23:59:59", loc)
	variable.DB.Redis.Set(fmt.Sprintf(common.RedisAgentIsTimeoutKey, agent.ID), t.Unix(), -1)

	cont, err := new(tables.Constitute).GetInfoByWhere(map[string]interface{}{"name": aar.School, "type": tables.SchoolType})
	if err != nil {
		return errors.NewErrInfo(10006, fmt.Errorf(errors.DatabaseMySqlOptionFail))
	}
	// 6. 该学校不存在
	if cont.ID == 0 {
		if _, err := new(tables.Constitute).InsertInfo(tables.Constitute{Name: aar.School, Type: tables.SchoolType, AgentID: &(agent.ID)}); err != nil {
			return errors.NewErrInfo(10007, fmt.Errorf(errors.DatabaseMySqlOptionFail))
		}
		cont, _ = new(tables.Constitute).GetInfoByWhere(map[string]interface{}{"name": aar.School, "type": tables.SchoolType})
	}

	// 7. 插入成功后，自动开通账户
	if aar.IsFlag {
		// 生成密码
		password := fmt.Sprintf("%06v", rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(1000000))
		var user tables.User
		user.RoleId = 3                  // 默认角色
		user.Level = tables.RolesLevel2  // 管理员类型
		user.Type = tables.UserTypeAdmin // 统一admin
		user.AgentID = agent.ID
		user.Name = aar.AgentName
		user.Phone = aar.ConnectPhone
		user.AccountName = &aar.ConnectPhone
		user.Password = tools.Md5DataString(password)
		user.Email = aar.Email
		user.School = cont.Name
		user.Grade = "" // grade 无
		user.ConstituteID = cont.ID
		user.CreateUserId = 0 // 自动创建
		// 添加用户
		rows, err := tables.AddUser(user)
		if err != nil || rows == 0 {
			return errors.NewErrInfo(errors.PublicErrorCode, fmt.Errorf("用户添加失败~"))
		}
		// 发送密码
		if err := sdk.SendMailInfo(sdk.MsgTypePassword, variable.Config.MailInfo.BusinessMail, sdk.MailInfo{RealName: aar.AgentName, AccountName: aar.ConnectPhone, Password: password, MailTo: aar.Email}); err != nil {
			return errors.NewErrInfo(errors.PublicErrorCode, fmt.Errorf("密码发送失败~"))
		}
		// 记录日志
		go func() {
			defer tools.RecoverGoroutine()
			new(tables.OptionLog).InsertOptionLog(ctx, rows, err)
		}()
	}

	return nil
}

// 获取客户列表
func GetAgentList(ctx *gin.Context, agr model.AgentGetReq, opt uint) ([]interface{}, int64, string, *errors.ErrRes) {
	var out []interface{}
	var count int64 = 0
	page := agr.Page
	pageSize := agr.Size
	where := make(map[string]interface{}, 0)
	whereStr := ""
	if len(agr.AgentName) != 0 {
		where["agent_name"] = agr.AgentName
	}
	if len(agr.ConnectPeople) != 0 {
		where["connect_people"] = agr.ConnectPeople
	}
	if len(agr.ConnectPhone) != 0 {
		where["connect_phone"] = agr.ConnectPhone
	}
	if len(agr.Counterpart) != 0 {
		where["counterpart"] = agr.Counterpart
	}
	if len(agr.CounterpartPhone) != 0 {
		where["counterpart_phone"] = agr.CounterpartPhone
	}
	if len(agr.Email) != 0 {
		where["email"] = agr.Email
	}
	if len(agr.School) != 0 {
		where["school"] = agr.School
	}
	if agr.SurplusStart >= 0 && agr.SurplusEnd >= 0 && agr.SurplusStart < agr.SurplusEnd {
		whereStr = fmt.Sprintf(" surplus_time > %d and surplus_time < %d", agr.SurplusStart, agr.SurplusEnd)
	}
	var agents []tables.Agent
	if pageSize != 0 {
		if d := variable.DB.MySQL.Where(where).Where(whereStr).Offset(int((page - 1) * pageSize)).Limit(int(pageSize)).Find(&agents).Offset(-1).Limit(-1).Count(&count); d.Error != nil {
			return out, 0, "", nil
		}
	} else {
		if d := variable.DB.MySQL.Where(where).Where(whereStr).Find(&agents).Count(&count); d.Error != nil {
			return out, 0, "", nil
		}
	}

	for _, v := range agents {
		var surplusTime = v.SurplusTime
		if surplusTime <= 0 {
			surplusTime = 0
		}
		out = append(out, model.AgentListResp{
			Id:               int64(v.ID),
			AgentName:        v.AgentName,
			ConnectPeople:    v.ConnectPeople,
			ConnectPhone:     v.ConnectPhone,
			Email:            v.Email,
			School:           v.School,
			Counterpart:      v.Counterpart,
			CounterpartPhone: v.CounterpartPhone,
			ServiceStartTime: v.ServiceStartTime.Format("2006-01-02"),
			ServiceEndTime:   v.ServiceEndTime.Format("2006-01-02"),
			SurplusTime:      surplusTime,
		})
	}
	if opt == 1 && out != nil {
		dir, _ := os.Getwd()
		fileName := tools.Md5DataString(time.Now().String()) + ".xlsx"
		localPath := dir + "/logs/" + fileName
		if _, err := tools.SaveExcle(localPath, "sheet1", common.AgentDetailHeader, out); err != nil {
			log.Logger.InfoF(ctx, "文件保存失败"+fileName)
			// 记录日志
			go func() {
				defer tools.RecoverGoroutine()
				new(tables.OptionLog).InsertOptionLog(ctx, int64(len(out)), err)
			}()
			return out, count, "", errors.NewErrInfo(10003, fmt.Errorf("文件导出失败，请重试"))
		} else {
			filePath := common.ExportFilePath + fileName
			sdk.FilePut(localPath, variable.Config.UfsInfo.BucketPrefix+filePath, sdk.XlsxMetaType)
			os.Remove(fileName)
			// 记录日志
			go func() {
				defer tools.RecoverGoroutine()
				new(tables.OptionLog).InsertOptionLog(ctx, int64(len(out)), err)
			}()
			return out, count, variable.Config.UfsInfo.UfsUrl + variable.Config.UfsInfo.BucketPrefix + filePath, nil
		}
	}

	return out, count, "", nil
}

// 获取客户列表
func GetAgentDetail(ctx *gin.Context, air model.AgentIdReq) (model.AgentDetailResp, *errors.ErrRes) {
	var adr model.AgentDetailResp
	out, err := new(tables.Agent).GetAgentByWhere(map[string]interface{}{"id": air.Id}, "")
	adr.Id = int64(out[0].ID)
	adr.AgentName = out[0].AgentName
	adr.ConnectPeople = out[0].ConnectPeople
	adr.ConnectPhone = out[0].ConnectPhone
	adr.Email = out[0].Email
	adr.School = out[0].School
	adr.Counterpart = out[0].Counterpart
	adr.CounterpartPhone = out[0].CounterpartPhone
	adr.ServiceStartTime = out[0].ServiceStartTime.Format("2006-01-02")
	adr.ServiceEndTime = out[0].ServiceEndTime.Format("2006-01-02")
	adr.SurplusTime = out[0].SurplusTime
	adr.IsSync = out[0].IsSync
	adr.Concurrent = out[0].Concurrent
	adr.AppletsConcurrent = out[0].AppletsConcurrent
	adr.AppletsUseDays = out[0].AppletsUseDays

	if err != nil {
		return adr, nil
	}
	return adr, nil
}

// 删除客户信息
func DeleteAgentById(ctx *gin.Context, adr model.AgentIdReq) *errors.ErrRes {
	err := new(tables.Agent).DeleteAgentById(uint(adr.Id))
	return errors.NewErrInfo(200, err)
}

// 更新客户信息
func UpdateAgent(ctx *gin.Context, aur model.AgentUpdateReq) *errors.ErrRes {
	startTime := time.Unix(aur.ServiceStartTime/1000, 0)
	endTime := time.Unix(aur.ServiceEndTime/1000, 0)
	surplusTime := tools.DiffNatureDays(endTime, time.Now())
	if surplusTime <= 0 {
		surplusTime = 0
	}
	redisCatchKey := fmt.Sprintf(common.RedisAgentCatch, aur.Id)
	_, err := variable.DB.Redis.Del(redisCatchKey).Result()
	updateInfo := map[string]interface{}{
		"email":              aur.Email,
		"connect_people":     aur.ConnectPeople,
		"connect_phone":      aur.ConnectPhone,
		"counterpart":        aur.Counterpart,
		"counterpart_phone":  aur.CounterpartPhone,
		"service_start_time": startTime.Format("2006-01-02") + " 23:59:59",
		"service_end_time":   endTime.Format("2006-01-02") + " 23:59:59",
		"surplus_time":       surplusTime,
		"is_sync":            aur.IsSync,
	}
	if aur.Concurrent != nil {
		updateInfo["concurrent"] = *aur.Concurrent
	}
	if aur.AppletsConcurrent != nil {
		updateInfo["applets_concurrent"] = *aur.AppletsConcurrent
	}
	if aur.AppletsUseDays != nil {
		updateInfo["applets_use_days"] = *aur.AppletsUseDays
	}

	//计算相差天数
	_, err = new(tables.Agent).UpdateAgentById(updateInfo, aur.Id)
	if err != nil {
		return errors.NewErrInfo(errors.DatabaseMysqlErrorCode, fmt.Errorf(errors.DatabaseMySqlOptionFail))
	}
	_, err = variable.DB.Redis.Del(redisCatchKey).Result()
	fmt.Sprintf("update redis error info :%+v\n", err)
	// 更新一下过期时间
	loc := time.FixedZone("UTC+8", 8*60*60)
	t, _ := time.ParseInLocation("2006-01-02 15:04:05", endTime.Format("2006-01-02")+" 23:59:59", loc)
	variable.DB.Redis.Set(fmt.Sprintf(common.RedisAgentIsTimeoutKey, aur.Id), t.UTC().Unix(), -1)

	return nil
}

// 计算客户时间
func CalculationServiceTime() error {
	agentObj := new(tables.Agent)
	agents, _ := agentObj.GetAgentList()
	var whereMap map[string]interface{}
	for _, v := range agents {
		surplusTime, _ := tools.GetDaysBetween2Date("2006-01-02", v.ServiceEndTime.Format("2006-01-02"), time.Now().UTC().Format("2006-01-02"))
		if surplusTime <= 0 {
			surplusTime = 0
		}
		whereMap = make(map[string]interface{}, 0)
		whereMap["surplus_time"] = surplusTime
		agentObj.UpdateAgentById(whereMap, int64(v.ID)) // 忽略是否更新成功
		// 转换时间戳
		timeStamp := v.ServiceEndTime.Unix()
		variable.DB.Redis.Set(fmt.Sprintf(common.RedisAgentIsTimeoutKey, v.ID), timeStamp, -1)
	}
	return nil
}

// 手动添加客户信息
func ManualAddAgent(ctx *gin.Context, req model.AddAgentParams) (*errors.ErrRes, map[string]string) {
	// 查询学校是否存在
	schools := new(tables.School).GetSchoolByName(req.School)
	if len(schools) != 1 {
		return errors.NewErrInfo(10003, fmt.Errorf("学校名字错误")), nil
	}
	agentObj := new(tables.Agent)
	// 判断agent是否已经存在
	agents, err := agentObj.GetAgentByWhere(map[string]interface{}{"school": req.School}, "")
	if err != nil {
		return errors.NewErrInfo(10003, fmt.Errorf(errors.DatabaseMySqlOptionFail)), nil
	}
	// 插入agent
	var agent tables.Agent
	if len(agents) > 0 {
		agent = agents[0]
	} else {

		startTime := time.Now()
		endTime := time.Now().Add(365 * 24 * time.Hour)
		surplusTime := tools.DiffNatureDays(endTime, time.Now())
		startTime, _ = time.Parse("2006-01-02 15:04:05", startTime.Format("2006-01-02")+" 23:59:59")
		endTime, _ = time.Parse("2006-01-02 15:04:05", endTime.Format("2006-01-02")+" 23:59:59")
		if surplusTime <= 0 {
			surplusTime = 0
		}
		a := tables.Agent{
			Type:             "school",
			Email:            uuid.New().String() + "@manual.com",
			AgentName:        req.School,
			ConnectPeople:    "知数",
			ConnectPhone:     "",
			Counterpart:      "知数",
			CounterpartPhone: "",
			ServiceStartTime: startTime,
			ServiceEndTime:   endTime,
			School:           req.School,
			SurplusTime:      int64(surplusTime),
			IsSync:           false,
		}
		log.Logger.InfoF(ctx, fmt.Sprintf("agent-->%+v", a))
		agent, err = agentObj.AddAgent(a)
	}
	if agent.ID == 0 || err != nil {
		log.Logger.ErrorMsgF(ctx, fmt.Sprintf("add agent err-->%+v", err))
		return errors.NewErrInfo(10005, fmt.Errorf(errors.DatabaseMySqlOptionFail)), nil
	}
	// 更新一下缓存数据
	loc := time.FixedZone("UTC+8", 8*60*60)
	t, _ := time.ParseInLocation("2006-01-02 15:04:05", agent.ServiceEndTime.Format("2006-01-02")+" 23:59:59", loc)
	variable.DB.Redis.Set(fmt.Sprintf(common.RedisAgentIsTimeoutKey, agent.ID), t.Unix(), -1)
	// 插入Constitute
	cont, err := new(tables.Constitute).GetInfoByWhere(map[string]interface{}{"name": req.School, "type": tables.SchoolType})
	if err != nil {
		return errors.NewErrInfo(10006, fmt.Errorf(errors.DatabaseMySqlOptionFail)), nil
	}
	if cont.ID == 0 {
		if _, err := new(tables.Constitute).InsertInfo(tables.Constitute{Name: req.School, Type: tables.SchoolType, AgentID: &(agent.ID)}); err != nil {
			return errors.NewErrInfo(10007, fmt.Errorf(errors.DatabaseMySqlOptionFail)), nil
		}
		cont, _ = new(tables.Constitute).GetInfoByWhere(map[string]interface{}{"name": req.School, "type": tables.SchoolType})
	}
	// 查询用户名是否已经使用
	users, err := new(tables.User).GetUsersByWhere(map[string]interface{}{"account_name": req.AccountName}, "*")
	if err != nil {
		return errors.NewErrInfo(10006, fmt.Errorf(errors.DatabaseMySqlOptionFail)), nil
	}
	if len(users) > 0 {
		return errors.NewErrInfo(10008, fmt.Errorf("用户名重复")), nil
	}
	defaultPwd := "123..."
	// 创造管理员
	var user tables.User
	user.RoleId = 3                  // 默认角色
	user.Level = 2                   // 管理员类型
	user.Type = tables.UserTypeAdmin // 统一admin
	user.AgentID = agent.ID
	user.Name = req.School + "-初始管理员"
	user.AccountName = &req.AccountName
	user.Password = tools.Md5DataString(defaultPwd)
	user.School = cont.Name
	user.Grade = "" // grade 无
	user.ConstituteID = cont.ID
	user.CreateUserId = 0 // 自动创建
	// 添加用户
	rows, err := tables.AddUser(user)
	if err != nil || rows == 0 {
		return errors.NewErrInfo(errors.PublicErrorCode, fmt.Errorf("用户添加失败~")), nil
	}
	// 记录日志
	go func() {
		defer tools.RecoverGoroutine()
		new(tables.OptionLog).InsertOptionLog(ctx, rows, err)
	}()
	return nil, map[string]string{
		"name":     req.AccountName,
		"pwd":      defaultPwd,
		"agent_id": fmt.Sprintf("%d", agent.ID),
	}
}

// 手动添加用户
func ManualAddUsers(ctx *gin.Context, req model.AddUsersParams) (*errors.ErrRes, map[string]string) {

	// 查询学校是否存在
	schools := new(tables.School).GetSchoolByName(req.School)
	if len(schools) != 1 {
		return errors.NewErrInfo(10003, fmt.Errorf("学校名字错误")), nil
	}
	agentObj := new(tables.Agent)
	// 判断agent是否已经存在
	agents, err := agentObj.GetAgentByWhere(map[string]interface{}{"school": req.School}, "")
	if err != nil {
		return errors.NewErrInfo(10003, fmt.Errorf(errors.DatabaseMySqlOptionFail)), nil
	}
	if len(agents) == 0 {
		return errors.NewErrInfo(10003, fmt.Errorf("agents 没有创建，请先创建该学校的agent")), nil
	}
	// 接收文件
	_, f, err := ctx.Request.FormFile("file")
	if err != nil {
		return errors.NewErrInfo(10003, fmt.Errorf("文件获取失败, "+err.Error())), nil
	}
	if !tools.CheckExcleName(f.Filename) {
		return errors.NewErrInfo(10003, fmt.Errorf("不能识别文件，请上传.xlsx格式的文件")), nil
	}

	f2, err := f.Open()
	if err != nil {
		return errors.NewErrInfo(10003, fmt.Errorf("文件打开异常, "+err.Error())), nil
	}
	b, _ := ioutil.ReadAll(f2)
	// 读取文件
	f3, err := xlsx.OpenBinary(b)
	if err != nil {
		return errors.NewErrInfo(10003, fmt.Errorf("文件读取异常, "+err.Error())), nil
	}
	out, err := f3.ToSlice()
	if err != nil {
		return errors.NewErrInfo(10003, fmt.Errorf("文件内容格式异常, "+err.Error())), nil
	}
	// 创建学院
	var academyMap = make(map[string]uint)
	var professionMap = make(map[string]uint)
	CreateConstitute := func(academy, profession string) uint {
		academyId, ok := academyMap[academy]
		// 创建院系
		if !ok || academyId == 0 {
			var a tables.Constitute
			variable.DB.MySQL.Table("constitute").Where("type = ? and belong_to_id = ? and name = ?", "academy", schools[0].ID, academy).Select("id,name,type,belong_to_id").Find(&a)
			if a.ID == 0 {
				a = tables.Constitute{Name: academy, Type: "academy", BelongToID: &schools[0].ID}
				err = variable.DB.MySQL.Table("constitute").Create(&a).Error
				if err != nil {
					panic(err)
				}
			}
			academyMap[academy] = a.ID
			academyId = a.ID
		}
		key := fmt.Sprintf("%s-%d", profession, academyId)
		pId, ok := professionMap[key]
		// 创建专业
		if !ok || pId == 0 {
			var p tables.Constitute
			variable.DB.MySQL.Table("constitute").Where("type = ? and belong_to_id = ? and name = ?", "profession", academyId, profession).Select("id,name,type,belong_to_id").Find(&p)
			if p.ID == 0 {
				p = tables.Constitute{Name: profession, Type: "profession", BelongToID: &academyId}
				err = variable.DB.MySQL.Table("constitute").Create(&p).Error
				if err != nil {
					panic(err)
				}
			}
			pId = p.ID
			professionMap[key] = pId
		}
		return pId
	}
	// 密码前缀处理
	var PwdPrefix = "YS"
	if req.PwdPrefix != "" {
		PwdPrefix = req.PwdPrefix
	}

	var conf tables.CommonConf
	variable.DB.MySQL.Table("common_conf").Where("conf_key = ? and remarks = ?", "school", req.School).Select("id").Find(&conf)
	if conf.ID == 0 {
		conf = tables.CommonConf{
			ConfKey:    "school",
			Type:       1,
			ConfValue:  PwdPrefix,
			Remarks:    req.School,
			ExtendInfo: "密码前缀",
		}
		err = variable.DB.MySQL.Table("common_conf").Create(&conf).Error
		if err != nil {
			panic(err)
		}
	}

	generatePwd := func(sno string) string {
		// 1. 根据学校名称获取学校前缀
		// 2. 生成密码
		// rsaPwd, _ := encrypt.RsaEncode(prefix + sno)

		userPwd, _ := encrypt.EncryptPassword(PwdPrefix + sno)
		return userPwd
	}
	allCount := 0
	// 导入
	var users []tables.User
	for s := 0; s < len(out); s++ {
		for i := 1; i < len(out[s]); i++ {
			if len(out[s][i]) < 6 {
				fmt.Println(s, i, out[s][i])
				continue
			}
			raw := out[s][i]
			name := raw[0]
			sno := raw[1]
			academy := raw[2]
			profession := raw[3]
			education := raw[4]
			grade := raw[5]
			var phone string
			if len(raw) >= 7 {
				phone = out[s][i][6] // 最后一列增加手机号
			}
			//constitute_id := q[academy][profession]
			if len(sno) > 12 {
				sno = sno[-(12 - len(sno)):]
			}
			// 创建学院和专业
			constitute_id := CreateConstitute(academy, profession)

			var user tables.User
			user.CreatedAt = time.Now().UTC()
			user.UpdatedAt = time.Now().UTC()
			user.Name = name
			user.Type = "normal"
			user.School = req.School
			user.Academy = academy
			user.Profession = profession
			user.Grade = grade
			user.AgentID = agents[0].ID
			user.RoleId = 0
			user.Sno = sno
			user.Level = 0
			user.ConstituteID = constitute_id
			user.Education = education
			user.Password = generatePwd(sno)
			if phone != "" {
				user.Phone = phone
			}
			allCount++
			// db.Table("users").Save(&user)
			users = append(users, user)
			if len(users) == 50 {
				variable.DB.MySQL.Table("users").Model(&user).CreateInBatches(users, len(users))
				users = []tables.User{}
				fmt.Println(s, i)
			}
			// db.Table("users").Where("sno = ? and school = ?", sno, InserSchool).FirstOrCreate(&user)
			// fmt.Println(user)
			// break
		}
	}
	if len(users) > 0 {
		variable.DB.MySQL.Table("users").CreateInBatches(users, len(users))
	}
	return nil, map[string]string{"插入数量": strconv.Itoa(allCount)}

}

// 手动更新客户信息
func ManualUpdateAgent(ctx *gin.Context, aur model.AgentUpdateReq) *errors.ErrRes {

	updateMap := map[string]interface{}{}
	if aur.Email != "" {
		updateMap["email"] = aur.Email
	}
	if aur.ServiceStartTime != 0 {
		startTime := time.Unix(aur.ServiceStartTime/1000, 0)
		updateMap["service_start_time"] = startTime.Format("2006-01-02") + " 23:59:59"
	}
	if aur.ServiceEndTime != 0 {
		endTime := time.Unix(aur.ServiceEndTime/1000, 0)
		surplusTime := tools.DiffNatureDays(endTime, time.Now())
		if surplusTime <= 0 {
			surplusTime = 0
		}
		updateMap["service_end_time"] = endTime.Format("2006-01-02") + " 23:59:59"
		updateMap["surplus_time"] = surplusTime
		// 更新一下过期时间
		loc := time.FixedZone("UTC+8", 8*60*60)
		t, _ := time.ParseInLocation("2006-01-02 15:04:05", endTime.Format("2006-01-02")+" 23:59:59", loc)
		variable.DB.Redis.Set(fmt.Sprintf(common.RedisAgentIsTimeoutKey, aur.Id), t.UTC().Unix(), -1)

	}
	if aur.Concurrent != nil {
		updateMap["concurrent"] = aur.Concurrent
	}

	//计算相差天数
	_, err := new(tables.Agent).UpdateAgentById(updateMap, aur.Id)
	if err != nil {
		return errors.NewErrInfo(errors.DatabaseMysqlErrorCode, fmt.Errorf(errors.DatabaseMySqlOptionFail))
	}
	return nil
}
